package com.data.listener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.data.entity.DataInfo;
import com.data.mapper.DataInfoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Excel 导入监听器 - 用于处理 Map 格式数据
 */
public class DataInfoImportListener extends AnalysisEventListener<Map<Integer, String>> {

    private static final Logger log = LoggerFactory.getLogger(DataInfoImportListener.class);

    private final List<DataInfo> dataList = new ArrayList<>();
    private final DataInfoMapper dataInfoMapper;
    private int rowIndex = 0;

    public DataInfoImportListener(DataInfoMapper dataInfoMapper) {
        this.dataInfoMapper = dataInfoMapper;
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
        rowIndex = context.readRowHolder().getRowIndex();

        // 跳过标题行
        if (rowIndex == 0) {
            return;
        }

        try {
            DataInfo info = new DataInfo();
            info.setNumber(StrUtil.trimToNull(data.get(0)));
            info.setTitle(StrUtil.trimToNull(data.get(1)));
            info.setLink(StrUtil.trimToNull(data.get(2)));
            info.setSource(StrUtil.trimToNull(data.get(3)));
            info.setTimeStr(StrUtil.trimToNull(data.get(4)));
            info.setContent(StrUtil.trimToNull(data.get(5)));
            info.setKeyword1(StrUtil.trimToNull(data.get(6)));
            info.setKeyword2(StrUtil.trimToNull(data.get(7)));
            info.setKeyword3(StrUtil.trimToNull(data.get(8)));
            info.setKeyword4(StrUtil.trimToNull(data.get(9)));
            info.setKeyword5(StrUtil.trimToNull(data.get(10)));
            info.setKeyword6(StrUtil.trimToNull(data.get(11)));
            info.setCollectSource(StrUtil.trimToNull(data.get(12)));

            // 校验关键字段
            if (info.getTitle() == null || info.getLink() == null || 
                info.getSource() == null || info.getTimeStr() == null) {
                log.warn("第{}行数据缺少关键字段，跳过: {}", rowIndex + 1, info);
                return;
            }

            // ⚠️ 去重判断：数据库中是否已存在相同记录
            LambdaQueryWrapper<DataInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DataInfo::getTitle, info.getTitle())
                   .eq(DataInfo::getLink, info.getLink())
                   .eq(DataInfo::getSource, info.getSource())
                   .eq(DataInfo::getTimeStr, info.getTimeStr());

            long count = dataInfoMapper.selectCount(wrapper);
            if (count == 0) {
                dataList.add(info);
            } else {
                log.info("第{}行数据已存在，跳过: {}", rowIndex + 1, info.getTitle());
            }

        } catch (Exception e) {
            log.error("解析第{}行数据时出错: {}", rowIndex + 1, data, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!dataList.isEmpty()) {
            log.info("准备批量插入 {} 条新数据", dataList.size());
            // 假设你使用了 MyBatis Plus 的 IService，可在 Service 中调用 saveBatch
        } else {
            log.info("没有新数据需要插入");
        }
    }

    // 提供方法供外部获取解析结果
    public List<DataInfo> getDataList() {
        return dataList;
    }
}